package br.embedded.ufcg.rmi;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.jgrapht.Graph;
import org.jgrapht.Graphs;
import org.jgrapht.generate.ScaleFreeGraphGenerator;
import org.jgrapht.graph.DefaultEdge;
import org.jgrapht.graph.SimpleWeightedGraph;

import br.edu.ufcg.embedded.mysocial.GraphCacheManager;
import br.edu.ufcg.embedded.mysocial.VertexGenerator;

public class Teste {
	
	private static int NUMBER_OF_VERTICES = 10000;
	private static double UPDATE_DEGREE = 0.01;
	private static Graph<String, DefaultEdge> graph;
	
	public static void main(String[] args)
	{
		createGraph();
		
		GraphCacheManager gcm = new GraphCacheManager(graph, new ArrayList<String>(graph.vertexSet()), 
				6, 10, 1000, "/home/daniel/Desktop/Testes/RMI/files/");
		long t1 = System.currentTimeMillis();
		gcm.run();
		long t2 = System.currentTimeMillis();
		
		System.out.println(t2 - t1);
		
		updateGraph();
		
		gcm = new GraphCacheManager(graph, new ArrayList<String>(graph.vertexSet()), 
				6, 10, 1000, "/home/daniel/Desktop/Testes/RMI/files/");
		t1 = System.currentTimeMillis();
		gcm.run();
		t2 = System.currentTimeMillis();
		
		System.out.println(t2 - t1);
	}
	
	private static void createGraph()
	{
		graph = new SimpleWeightedGraph<String, DefaultEdge>(DefaultEdge.class);
		ScaleFreeGraphGenerator<String, DefaultEdge> generator = new ScaleFreeGraphGenerator<String, DefaultEdge>(NUMBER_OF_VERTICES);
		generator.generateGraph(graph, new VertexGenerator(), null);
		generator = null;
	}
	
	private static void updateGraph()
	{
		List<String> list = new ArrayList<String>(graph.vertexSet());
		int[] vertexDegrees = new int[2 * graph.edgeSet().size()];
		
		int index = 0;
		
		for (int i = 0; i < list.size(); i++) {
			int degree = Graphs.neighborListOf(graph, list.get(i)).size();
			
			for (int j = 0; j < degree; j++)
				vertexDegrees[index++] = i;
		}
		
		Random random = new Random();
		
		int newEdges = ( (int) (NUMBER_OF_VERTICES * UPDATE_DEGREE));
		int k = 0;
		
		while (k < newEdges)
		{
			int sourceIndex = random.nextInt(vertexDegrees.length);
			int targetIndex = random.nextInt(vertexDegrees.length);
			
			String sourceVertex = list.get(vertexDegrees[sourceIndex]);
			String targetVertex = list.get(vertexDegrees[targetIndex]);
			
			if (!sourceVertex.equalsIgnoreCase(targetVertex) && !(graph.containsEdge(sourceVertex, targetVertex) && graph.containsEdge(targetVertex, sourceVertex)))
			{
				graph.addEdge(sourceVertex, targetVertex);
				k++;
			}
		}
	}

}
